<template>
  <!-- 主体 -->
  <view v-if="contentDisplay" id="content" :class="'content'">
    <!-- 主体卡片区域 -->
    <view :class="devtools==='ios'?'content-card-fa-ios':'content-card-fa'">
      <!-- 路线 -->
      <view class="card card-route">
        <view class="card-title">{{ name }}</view>
        <view class="card-route-title">{{ packages.name }}</view>
      </view>
      <!-- 出行日期 -->
      <selfCalendar :datetime="date" :uid="uid" @changeDate="changeDate" />
      <!-- 上车地点 -->
      <view class="card card-car">
        <view class="card-title">上车地点</view>
        <view class="card-car-date">时间：{{ packages.in_time }}</view>
        <view class="card-car-place">地点：{{ packages.in_car }}</view>
      </view>
      <!-- 订单联系人 -->
      <orderContacts
        :query="orderContactsQuery"
        @changeInput="contactsChangeInput"
        @changeLanguage="contactsChangeLanguage"
        @choicePassenger="contactsChoicePassenger"
      />
      <!-- 可购买资源 -->
      <view v-for="(item,index) in resource" :key="index" class="card-resource">
        <!-- 吸顶区域 -->
        <view class="sticky">
          <view class="card-sticky-flex">
            <view class="card-sticky-title">{{ item.name }}</view>
            <view class="card-sticky-price">￥{{ item.stocks.price }}</view>
          </view>
          <view class="card-sticky-flex">
            <view
              class="card-sticky-nums"
            >购买数量{{ item.min_purchase>1?'（最少'+item.min_purchase+'张）':'' }}</view>
            <view class="card-purchase-quantity-right">
              <view class="card-purchase-quantity-right-reduce" @click="rectangle(index,name)">
                <i class="reduce-rectangle" />
              </view>
              <view class="card-purchase-quantity-right-number">
                <input type="number" :data-index="index" :data-name="name" :value="item.number" @focus="getNumber(index)" @blur="verification">
              </view>
              <view class="card-purchase-quantity-right-add" @click="add(index,name)">
                <i class="reduce-rectangle" />
                <i class="reduce-rectangle-rotate" />
              </view>
            </view>
          </view>
          <view
            class="card-sticky-explain"
            :style="item.list.length>0?'padding-bottom: 32rpx; border-bottom: 2rpx solid #f1f1f1;':''"
          >{{ item.content }}</view>
        </view>
        <!-- 非吸顶区域 -->
        <view
          class="not-sticky"
        >
          <orderContacts
            :list="item.list"
            :resource-index="index"
            @changeInput="contactsChangeInput"
            @changeLanguage="contactsChangeLanguage"
            @choicePassenger="contactsChoicePassenger"
            @changeID="contactsChangeID"
          />
        </view>
      </view>
      <!-- 告罄列表 -->
      <view v-for="(item,index) in exhaustedList" :key="index" class="card card-exhausted">
        <view class="card-exhausted-flex">
          <view class="card-exhausted-title">{{ item.name }}</view>
          <view class="card-exhausted-price">￥{{ item.stocks.price }}</view>
        </view>
        <view class="card-exhausted-flex">
          <view class="card-exhausted-nums">购买数量</view>
          <image class="card-exhausted-image" src="@/static/image/order/exhausted.png" />
        </view>
        <view class="card-exhausted-explain">{{ item.content }}</view>
      </view>
      <!-- 出游人须知 -->
      <view class="card card-explain">
        <view class="card-title">出游人需知</view>
        <view
          class="card-explain-title"
        >出行时请携带本人身份证件，如所购买票种为社保金优惠票、残疾人票、离休票、现役军人票、消防票、医护票等特殊票种的，请携带相关证件检票时与身份证件一同出示。</view>
      </view>
    </view>
    <!-- 底部边框 -->
    <view :class="devtools==='ios'?'payment payment-ios':'payment'">
      <view class="payment-total">
        合计：
        <text>{{ '￥'+totalPrice }}</text>
      </view>
      <button class="payment-button" @click="ticketOrder">前往支付</button>
    </view>
    <!-- 弹出框 -->
    <choicePopup
      :show="show"
      :query="choicePopupQuery"
      @close="choicePopupClose"
      @updataId="updataId"
      @updataTraveler="updataTraveler"
    />
  </view>
</template>
<script>
import { getSelfDetails, getSelfOrder } from '@/api/self'
import selfCalendar from '@com/self/selfCalendar'
import orderContacts from '@com/self/orderContacts'
import choicePopup from '@com/order/choicePopup'
import { get } from '@utils/storage'
import { showToast } from '@utils/myApproach'
export default {
  components: { selfCalendar, orderContacts, choicePopup },
  data() {
    return {
      rect: 0, // 页面滚动距离
      menutop: '', // 组件距离顶部的距离
      contentDisplay: false,
      fixedIndex: null,
      uid: null,
      date: null,
      name: null,
      totalPrice: 0,
      productUid: null,
      show: false,
      packages: null,
      resource: null,
      exhaustedList: null,
      antiShake: null,
      state: true,
      exhausted_margin_top: 30,
      orderContactsQuery: {
        language: 'EN',
        first_name: '',
        last_name: '',
        telephone: ''
      },
      choicePopupQuery: {
        type: 'traveler',
        id_type: '',
        index: null,
        code: null,
        personType: null
      }
    }
  },
  computed: {
    devtools() {
      return get('devtools')
    }
  },
  onLoad(option) {
    this.uid = option.uid
    this.date = option.date
    this.name = option.name
    this.productUid = option.productUid
    this.getSelfDetails()
  },
  methods: {
    getSelfDetails() {
      getSelfDetails(this.uid, this.date).then((res) => {
        this.packages = res.data.data.package
        this.resource = res.data.data.resource
        this.exhaustedList = []
        // 两个写在一起会有数据冲突，
        this.resource.forEach((item, index, array) => {
          array[index].number = 0
          array[index].list = []
        })
        this.resource.forEach((item, index, array) => {
          if (item.stocks.available_stock === 0) {
            this.exhaustedList.push(item)
            array.splice(index, 1)
          }
        })
        this.orderContactsQuery = {
          language: 'EN',
          first_name: '',
          last_name: '',
          telephone: ''
        }
        this.contentDisplay = true
      })
    },
    // 选择日期
    changeDate(date) {
      this.date = date
      this.getSelfDetails()
    },
    // 切换语言
    contactsChangeLanguage(language) {
      // 订单联系人

      if (language.resourceIndex !== null) {
        this.resource[language.resourceIndex].list[language.index].language = language.language === 'EN' ? 'CN' : 'EN'
        this.resource[language.resourceIndex].list[language.index].first_name = ''
        this.resource[language.resourceIndex].list[language.index].last_name = ''
        this.$forceUpdate()
      } else {
        // 订单联系人

        this.orderContactsQuery.language = language.language === 'EN' ? 'CN' : 'EN'
        this.orderContactsQuery.first_name = ''
        this.orderContactsQuery.last_name = ''
      }
    },
    // 同步input
    contactsChangeInput(e) {
      const model = e.e.currentTarget.dataset.model
      if (e.index !== null) {
        const index = e.e.currentTarget.dataset.index
        const resourceIndex = e.index
        const model = e.e.currentTarget.dataset.model

        this.resource[resourceIndex].list[index][model] = e.e.detail.value
        console.log(resourceIndex, index)
      } else {
        this.orderContactsQuery[model] = e.e.detail.value
      }
      console.log(this.resource)
      this.$forceUpdate()
    },
    // 选择乘客
    contactsChoicePassenger(index) {
      if (index.resourceIndex !== null) {
        this.choicePopupQuery.type = 'traveler'
        this.choicePopupQuery.index = index
        this.show = true
      } else {
        this.choicePopupQuery.type = 'traveler'
        this.choicePopupQuery.index = null
        this.show = true
      }
    },
    // 选择证件类型
    contactsChangeID(index) {
      if (this.packages.place_condition.allow_id.length > 1) {
        this.show = true
        this.choicePopupQuery.type = 'ID'
        this.choicePopupQuery.index = index
        this.choicePopupQuery.id_type = this.resource[index.resourceIndex].list[index.index].id_type
      } else {
        showToast('该资源只支持' + this.$commonDictMap[this.packages.place_condition.allow_id[0]])
      }
    },
    choicePopupClose() {
      this.show = false
    },
    updataId(data) {
      //
      this.resource[data.index.resourceIndex].list[data.index.index].id_type = data.value
      this.resource[data.index.resourceIndex].list[data.index.index].id_no = ''
    },
    updataTraveler(data) {
      const existence = this.packages.place_condition.allow_id.findIndex(item => {
        return data.item.id_type_display === item
      })
      if (existence < 0) {
        showToast('该资源只支持' + this.$commonDictMap[this.packages.place_condition.allow_id[0]])
      } else {
        if (data.index) {
          const listItem = {
            id_no: data.item.id_no,
            telephone: data.item.telephone,
            first_name: data.item.full_name,
            language: data.item.name_type_display === 'CN' ? 'EN' : 'CN',
            id_type: data.item.id_type_display,
            listItemIndex: this.resource[data.index.resourceIndex].list[data.index.index].listItemIndex
          }
          this.resource[data.index.resourceIndex].list.splice(data.index.index, 1, listItem)
        } else {
          const item = data.item
          this.orderContactsQuery.language =
          item.name_type_display === 'CN' ? 'EN' : 'CN'
          this.orderContactsQuery.telephone = item.telephone
          this.orderContactsQuery.first_name = item.full_name
        }
      }
    },
    rectangle(index, name) {
      if (this.resource[index].number === 0) {
        showToast('数值不能小于0')
      } else {
        if (this.resource[index].number > this.resource[index].min_purchase) {
          this.resource[index].number = this.resource[index].number - 1
          this.resource[index].list.pop()
        } else {
          this.resource[index].number = this.resource[index].number - this.resource[index].min_purchase
          for (var i = 0; i < this.resource[index].min_purchase; i++) {
            this.resource[index].list.pop()
          }
        }
      }
      this.totalPrice = this.prices()
      console.log(this.resource)
      this.$forceUpdate()
    },
    add(index, name) {
      if (this.resource[index].number < this.resource[index].max_purchase) {
        if (this.resource[index].number === 0) {
          this.resource[index].number = this.resource[index].number + this.resource[index].min_purchase
          for (var i = 0; i < this.resource[index].min_purchase; i++) {
            const listItem = {
              id_no: '',
              telephone: '',
              first_name: '',
              last_name: '',
              language: 'EN',
              id_type: this.packages.place_condition.allow_id[0],
              listItemIndex: i
            }
            this.resource[index].list.push(listItem)
            this.$forceUpdate()
          }
        } else {
          this.resource[index].number = this.resource[index].number + 1
          const listItem = {
            id_no: '',
            telephone: '',
            first_name: '',
            last_name: '',
            language: 'EN',
            id_type: this.packages.place_condition.allow_id[0],
            listItemIndex: i
          }
          this.resource[index].list.push(listItem)
          this.$forceUpdate()
        }
      } else {
        showToast(this.resource[index].name + '单次购买不可超过' + this.resource[index].max_purchase + '张')
      }
      this.totalPrice = this.prices()
      this.$forceUpdate()
    },
    getNumber(index) {
      this.resource[index].storageNumber = this.resource[index].number
      this.resource[index].number = null
      this.$forceUpdate()
    },
    verification(e) {
      const index = e.currentTarget.dataset.index
      // const name = e.currentTarget.dataset.name
      const data = parseInt(e.detail.value)
      if (String(data) === 'NaN') {
        this.resource[index].number = this.resource[index].storageNumber
        showToast('请输入数字')
      } else if (data > 0 && data < this.resource[index].min_purchase) {
        showToast(this.resource[index].name + '最低购买数量为' + this.resource[index].min_purchase + '张')
        this.resource[index].number = this.resource[index].storageNumber
      } else {
        if (data < 0) {
          this.resource[index].number = this.resource[index].storageNumber
          showToast('数值不能小于0')
        } else if (data > this.resource[index].max_purchase) {
          this.resource[index].number = this.resource[index].storageNumber
          showToast(this.resource[index].name + '单次购买不可超过' + this.resource[index].max_purchase + '张')
        } else {
          this.resource[index].number = data
          const length = this.resource[index].list.length
          if (length < this.resource[index].number) {
            for (var i = length; i < this.resource[index].number; i++) {
              const listItem = {
                id_no: '',
                telephone: '',
                first_name: '',
                last_name: '',
                language: 'EN',
                id_type: this.packages.place_condition.allow_id[0],
                listItemIndex: i
              }
              this.resource[index].list.push(listItem)
            }
          } else if (length > this.resource[index].number) {
            for (var j = length; j > this.resource[index].number; j--) {
              this.resource[index].list.pop()
            }
          }
        }
      }
      this.totalPrice = this.prices()
      this.$forceUpdate()
    },
    // 计算合计价格
    prices() {
      var prices = 0
      this.resource.forEach((resourceItem, resourceIndex, resourceArray) => {
        prices = prices + resourceItem.stocks.price * resourceItem.number
      })
      return prices
    },
    // 前往支付
    ticketOrder() {
      //
      this.state = true
      // 验证订单联系人是否是空
      if (this.orderContactsQuery.first_name === '') return showToast('姓名不能为空')
      if (this.orderContactsQuery.telephone === '') return showToast('联系方式不能为空')

      // 验证资源是否是空

      this.resource.forEach((resourceItem, resourceIndex, resourceArray) => {
        resourceItem.list.forEach((listItem, listIndex, listArray) => {
          if (listItem.first_name === '') {
            showToast('姓名不能为空')
            this.state = false
            return
          }
          if (listItem.id_no === '') {
            showToast('证件不能为空')
            this.state = false
            return
          }
        })
      })
      // 是否通过循环验证
      if (this.state) {
        const selfData = {
          'product': this.productUid,
          'package': this.uid,
          'date': this.date,
          'resourceEntity': [],
          'contact': {
            'name': this.orderContactsQuery.first_name,
            'telephone': this.orderContactsQuery.telephone
          }
        }
        // 循环输入resourceEntity
        this.resource.forEach((resourceItem, resourceIndex, resourceArray) => {
          if (resourceItem.list.length > 0) {
            const resourceEntityItem = {
              'resource': resourceItem.uid,
              'guest': []
            }
            resourceItem.list.forEach((listItem, listIndex, listArray) => {
              const guestItem = {
                'id_type': listItem.id_type,
                'id_no': listItem.id_no,
                'name': listItem.first_name
              }
              resourceEntityItem.guest.push(guestItem)
            })
            selfData.resourceEntity.push(resourceEntityItem)
          }
        })
        // 调用接口
        getSelfOrder(selfData).then((res) => {
          if (res.data.code === 200) {
            selfData.prices = res.data.data.price
            selfData.packages = this.packages
            selfData.name = this.name
            selfData.resource = this.resource
            uni.redirectTo({
              url: `/pages/payment/payment?query=${JSON.stringify(selfData)}&orderUid=${res.data.data.orderUid}&type='self'`
            })
          } else {
            showToast('创建订单失败')
          }
        })
      }
      // getSelfOrder().then()
    }
  }
}
</script>
<style scoped>
.content {
  min-height: calc(100vh - 30rpx);
  padding-top: 30rpx;
  background-color: #f8f8f8;
}
.content-card-fa {
  padding-bottom: 140rpx;
}
.content-card-fa-ios {
  padding-bottom: 206rpx;
}
.card {
  width: 710rpx;
  background-color: #ffffff;
  margin-left: 20rpx;
  box-shadow: 0rpx 0rpx 20rpx 0px rgba(0, 0, 0, 0.1);
  border-radius: 8rpx;
  padding-top: 30rpx;
  padding-bottom: 30rpx;
  margin-top: 30rpx;
}
.card-title {
  font-size: 36rpx;
  color: #000000;
  font-weight: bold;
  margin-left: 30rpx;
}
/* 路线 */
.card-route {
  margin-top: 0;
}
.card-route-title {
  font-size: 28rpx;
  color: #306de9;
  margin-left: 30rpx;
  margin-top: 30rpx;
  font-weight: normal;
}
/* 上车地点 */
.card-car {
  font-size: 28rpx;
  color: #000000;
}
.card-car-date {
  margin-left: 30rpx;
  margin-top: 20rpx;
}
.card-car-place {
  margin-left: 30rpx;
  margin-top: 20rpx;
}
/* 可购买资源 */
.card-resource {
  width: 710rpx;
  background-color: #ffffff;
  margin-left: 20rpx;
  box-shadow: 0rpx 0rpx 20rpx 0px rgba(0, 0, 0, 0.1);
  border-radius: 8rpx;
  padding-bottom: 30rpx;
  margin-top: 30rpx;
}
.card-sticky-flex {
  display: flex;
  justify-content: space-between;
  color: #000000;
  font-size: 36rpx;
  font-weight: bold;
  padding-top: 30rpx;
}
.card-sticky-title {
  margin-left: 30rpx;
}
.card-sticky-price {
  margin-right: 30rpx;
  color: #dd3939;
}
.card-sticky-nums {
  font-size: 28rpx;
  font-weight: normal;
  line-height: 108rpx;
  margin-left: 30rpx;
}
/* 购买数量 */
.card-purchase-quantity-right {
  width: 176rpx;
  height: 48rpx;
  border: 2rpx solid #cccccc;
  display: flex;
  text-align: center;
  margin-top: 30rpx;
  margin-right: 30rpx;
}
.card-purchase-quantity-right-reduce {
  width: 48rpx;
  height: 48rpx;
  border-right: 2rpx solid #cccccc;
}
.reduce-rectangle {
  width: 20rpx;
  height: 4rpx;
  background-color: #9b9b9b;
  text-align: left;
  margin-left: 16rpx;
  margin-top: 24rpx;
}
.reduce-rectangle-rotate {
  position: absolute;
  width: 20rpx;
  height: 4rpx;
  background-color: #9b9b9b;
  text-align: left;
  left: 16rpx;
  top: 24rpx;
  transform: rotate(90deg);
}
.card-purchase-quantity-right-number {
  height: 48rpx;
  width: 76rpx;
  line-height: 48rpx;
  font-weight: normal;
}
.card-purchase-quantity-right-add {
  position: relative;
  width: 48rpx;
  height: 48rpx;
  border-left: 2rpx solid #cccccc;
}
.card-sticky-explain {
  font-size: 24rpx;
  font-weight: normal;
  margin-left: 20rpx;
  width: 660rpx;
  padding-left: 10rpx;
  color: #9b9b9b;
}
/* 告罄列表 */
.card-exhausted-flex {
  display: flex;
  justify-content: space-between;
  color: #9b9b9b;
  font-size: 36rpx;
  font-weight: bold;
}
.card-exhausted-title {
  margin-left: 30rpx;
}
.card-exhausted-price {
  margin-right: 30rpx;
}
.card-exhausted-nums {
  font-size: 28rpx;
  font-weight: normal;
  line-height: 108rpx;
  margin-left: 30rpx;
}
.card-exhausted-image {
  width: 80rpx;
  height: 80rpx;
  margin-right: 30rpx;
  margin-top: 14rpx;
  margin-bottom: 14rpx;
}
.card-exhausted-explain {
  font-size: 24rpx;
  font-weight: normal;
  margin-left: 30rpx;
  padding-right: 30rpx;
  color: #9b9b9b;
}
/* 出游人须知 */
.card-explain-title {
  font-size: 24rpx;
  margin-left: 30rpx;
  padding-right: 30rpx;
  margin-top: 24rpx;
  line-height: 34rpx;
}
/* 支付按钮 */
.payment {
  position: fixed;
  bottom: 0;
  z-index: 99;
  width: 750rpx;
  height: 120rpx;
  background-color: #ffffff;
  display: flex;
  justify-content: space-between;
}
.payment-ios {
  height: 186rpx;
}
.payment-total {
  margin-left: 50rpx;
  margin-top: 36rpx;
  font-size: 28rpx;
}
.payment-total > text {
  font-weight: 700;
  font-size: 32rpx;
  color: #dd3939;
}
.payment-button {
  margin: 0;
  padding: 0;
  margin-top: 20rpx;
  margin-right: 30rpx;
  background-color: #306de9;
  font-size: 32rpx;
  color: #ffffff;
  font-weight: 700;
  width: 240rpx;
  height: 80rpx;
  text-align: center;
  line-height: 80rpx;
}
/* 吸顶 */
.sticky {
  position: sticky; /* 这个是吸顶粘附关键属性 */
  top: 0;
  z-index: 9;
  background-color: #ffffff;
}
</style>
